<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 50px;
            height: 50px;
        }
    </style>
</head>

<body>

    <div class="box"></div>

    <script>
        // 根据数据 实现红绿灯
        const lights = [{
            color: 'red',
            duration: 5000
        }, {
            color: 'yellow',
            duration: 2000
        }, {
            color: 'green',
            duration: 5000
        }]



        let box = document.getElementsByClassName('box')[0]
        
        box.style.backgroundColor = lights[0].color

        let light = (function() {
            let i = 0

            return function() {
                if (i > 2) i = 0
                setTimeout(() => {
                    box.style.backgroundColor = lights[i].color
                    i++;
                    light()
                }, lights[i].duration)

            }
        })()

        light()
    </script>
</body>

</html>